package udp;

import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;

public class EchoClientHandler extends SimpleChannelInboundHandler<DatagramPacket>{

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet) {
        ByteBuf buf = packet.copy().content();
        byte[] req = new byte[buf.readableBytes()];
        buf.readBytes(req);
        String str = new String(req, StandardCharsets.UTF_8);
        System.out.println("收到的消息：" + str);
        String[] list = str.split("::");
        //如果是A 则发送
        if(list[0].equals("ok")){
            String ip = list[1];
            String port = list[2];
            new Thread(() -> {
                while (true) {
                    System.out.print("输入消息：");
                    Scanner scanner = new Scanner(System.in);
                    String in = scanner.nextLine();
                    String msg = "打洞信息" + in;
                    ctx.writeAndFlush(new DatagramPacket(
                            Unpooled.copiedBuffer(msg.getBytes()), new InetSocketAddress(ip, Integer.parseInt(port))));
                }
            }).start();
        }
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("发送wait等待其它客户端连接，conn连接到其它客户端");
        Scanner scanner = new Scanner(System.in);
        String in = scanner.nextLine();
        ctx.writeAndFlush(new DatagramPacket(
                Unpooled.copiedBuffer(in.getBytes()),
                new InetSocketAddress("121.36.12.15", 8088)));
        super.channelActive(ctx);
    }
}